<template>
  <el-upload ref="upload" class="upload-demo" v-model:file-list="fileList" action="#" :limit="1" :on-remove="fileRemove"
    :on-exceed="handleExceed" :auto-upload="false" :on-change="FileChange">
    <template #trigger>
      <el-button type="primary">select file</el-button>
    </template>
    <!-- <el-button class="ml-3" type="success" @click="submitUpload">
      upload to server
    </el-button> -->
    <template #tip>
      <div class="el-upload__tip text-red">
        只能上传一个文件,新文件会自动覆盖上一个文件
      </div>
    </template>
  </el-upload>
</template>

<script setup lang='ts'>
import { ref } from 'vue'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus'
// 怎么设计 1 文件files文件上传传递回去 2 关闭清空数据
const emit = defineEmits(['fileUp'])
const upload = ref<UploadInstance>()
const fileList = ref<UploadUserFile[]>([
])
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const FileChange: UploadProps['onChange'] = (uploadFile: any) => {
  // console.log(uploadFile.raw); 
  fileList.value = []
  fileList.value.push(uploadFile.raw)
  emit('fileUp', fileList.value)
}
const submitUpload = () => {
  upload.value!.submit()
}
const fileRemove = (file) => {
  console.log(file, '==');
  console.log(fileList.value);
  emit('fileUp', fileList.value)
}
const clearFile = () => {
  upload.value!.clearFiles()
  fileList.value = []
}
defineExpose({
  clearFile
})
</script>
<style scoped lang='scss'></style>